#include "modulesfactory.h"
#include "defenderinterface.h"

#include <QPluginLoader>
#include <QDebug>
#include <QFileInfo>
#include <QDir>

class ModulesFactoryPrivate
{
    ModulesFactory* q_ptr;
    Q_DECLARE_PUBLIC(ModulesFactory)

public:
    static QString mSearchPath;
};
QString ModulesFactoryPrivate::mSearchPath = "/usr/lib/";

ModulesFactoryPrivate* ModulesFactory::d_ptr = new ModulesFactoryPrivate;

static QString getModule(const QString& name) {
    QStringList fl;
    QString path = ModulesFactoryPrivate::mSearchPath;
    if (!(path.endsWith("/"))) {
        path.append('/');
    }
    fl << BINARY_FILE(path, name);
    fl << BINARY_FILE(path, BINARY_FILE_1(name));
    fl << BINARY_FILE(path, BINARY_FILE_2(name));
    fl << BINARY_FILE(path, BINARY_FILE_3(name));
    fl << BINARY_FILE(path, BINARY_FILE_4(name));
    for (const QString& fn : fl) {
        QFileInfo file(fn);
        if (file.exists() && file.isFile()) {
            return  fn;
        }
    }
    return QString::null;
}

ModulesFactory::ModulesFactory(QObject *parent) : QObject(parent)
{

}

void ModulesFactory::setSearchPath(const QString &path)
{
    d_ptr->mSearchPath = path;
}

QWidget *ModulesFactory::createModule(const QString &name)
{
    QString fn = getModule(name);
    if (fn.isNull()) {
        qDebug() << name << "module not found";
        return nullptr;
    }

    QPluginLoader loader(fn);
    QObject *instance = loader.instance();
    if (instance) {
        DefenderInterface* inter = qobject_cast<DefenderInterface*>(instance);
        if (inter) {
            return inter->cretateWidget();
        }
    } else {
        qDebug() << "error" << fn << loader.errorString();
    }
    return nullptr;
}


